
/**
 * Copyright 2009 cestum.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package org.waveprotocol.wave.model.document.operation.impl.util {
import org.waveprotocol.wave.model.document.operation.impl.AnnotationBoundaryMapImpl;

import org.waveprotocol.wave.model.util.Preconditions;

public final class ArrBuilder {
	private static  var EMPTY_ARRAY:Array= new Array(0);
	
	private var changeKeys:Array= EMPTY_ARRAY;
	private var changeOldValues:Array= EMPTY_ARRAY;
	private var changeNewValues:Array= EMPTY_ARRAY;
	private var endKeys:Array= EMPTY_ARRAY;
	
	public function ArrBuilder() {
	}
	
	public function build():AnnotationBoundaryMapImpl {
		return new AnnotationBoundaryMapImpl(endKeys, changeKeys,
			changeOldValues, changeNewValues);
	}
	
	public function initializationEnd(keys:Array):ArrBuilder {
		endKeys = keys;
		return this;
	}
	
	public function initializationValues(pairs:Array):ArrBuilder {
		if (pairs.length % 2!= 0) {
			throw new Error("pairs must be even in size");
		}
		
		var keys:Array= new Array(pairs.length / 2);
		var values:Array= new Array(pairs.length / 2);
		for (var i:int= 0; i < keys.length; i++) {
			keys[i] = pairs[i * 2];
			values[i] = pairs[i * 2+ 1];
		}
		changeKeys = keys;
		changeOldValues = new String[keys.length];
		changeNewValues = values;
		return this;
	}
	
	public function updateValues3(keys:Array, oldValues:Array,
								  newValues:Array):ArrBuilder {
		Preconditions.checkArgument(keys.length == oldValues.length
			&& keys.length == oldValues.length,
			"Parallel arrays must have same length");
		changeKeys = keys;
		changeOldValues = oldValues;
		changeNewValues = newValues;
		return this;
	}
	
	public function updateValues(triplets:Array):ArrBuilder {
		if (triplets.length % 3!= 0) {
			throw new Error(
				"Triplets must be a multiple of 3 in size");
		}
		
		var keys:Array= new Array(triplets.length / 3);
		var oldValues:Array= new Array(triplets.length / 3);
		var newValues:Array= new Array(triplets.length / 3);
		for (var i:int= 0; i < keys.length; i++) {
			keys[i] = triplets[i * 3];
			oldValues[i] = triplets[i * 3+ 1];
			newValues[i] = triplets[i * 3+ 2];
		}
		return updateValues3(keys, oldValues, newValues);
	}
}
}